<?php
declare (strict_types=1);

namespace app\middleware;

use app\factory\Factory;
use app\factory\model\RequestAgreement;
use app\factory\tool\frameVerify\EncryptionTool;
use app\factory\tool\TokenCreate;
use app\factory\tool\VerifyIsTest;
use think\Response;

class TokenVerify
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 处理 OPTIONS 请求
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            header("'Access-Control-Allow-Credentials: true");
            header("Access-Control-Allow-Origin: *");
            header("Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token,cy-type-key");
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
            exit; // 直接退出，不走后序流程
        }
        $tool = app(VerifyIsTest::TOOL_VERIFY_IS_TEST);
        //是否测试
        $flag = $tool->startVerify($request);
        if ($flag) {
            return $next($request);
        }
        //不需要验证的url
        $arr = [

        ];
        $url = $request->url();
        if ($url == "/") {
            return $next($request);
        }
        foreach ($arr as $path) {
            if (strpos($url, $path) !== false) {
                // URL 包含在不需要验证的列表中
                return $next($request);
            }
        }
        //获取请求头中的token
        $token = $request->header('token');
        if (empty($token)) {
            return Response::create(['errMsg' => "请先登录！", 'errCode' => FAIL, "content" => []], 'json', 403);
        }
        //解析token
        $tokenTool = app(TokenCreate::TOOL_TOKEN_CREATE);
        //(数组)解析token(token)
        $arr = $tokenTool->decodeToken($token);
        if ($arr['code'] == 500) {
            return Response::create(['errMsg' => $arr['msg'], 'errCode' => FAIL, "content" => []], 'json', 403);
        }
        //保存token
        $requestAggr = app(RequestAgreement::MODEL_REQUEST_AGREEMENT);
        //用户Token
        $requestAggr->setToken($token);
        //用户ID
        $requestAggr->setUserId($arr['data']['data']->userId);

        return $next($request);
    }


}
